package app.client;

import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

class ImagePreviewer extends JLabel {
    public ImagePreviewer(JFileChooser fileChooser) {
        setPreferredSize(new Dimension(100, 100));
        setBorder(BorderFactory.createEtchedBorder());

        fileChooser.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent e) {
                if (e.getPropertyName().equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
                    File file = (File) e.getNewValue();

                    if (file == null) {
                        setIcon(null);

                        return;
                    }

                    ImageIcon icon = new ImageIcon(file.getPath());

                    if (icon.getIconWidth() > getWidth()) icon =
                            new ImageIcon(icon.getImage().getScaledInstance(getWidth(), -1, Image.SCALE_DEFAULT));
                    setIcon(icon);
                }
            }
        });
    }
}